package org.dreamwork.hyacinth.jasmine;

import org.dreamwork.misc.MimeTypeManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-3-20
 * Time: 下午6:26
 */
public class URLImageCreator implements IImageCreator {
    private String contentType = "image";
    private ByteArrayOutputStream baos = new ByteArrayOutputStream ();

    private static final int MAX_LENGTH = 10000;

    public URLImageCreator (URL url) throws IOException {
        String protocol = url.getProtocol ();
        if ("http".equalsIgnoreCase (protocol))
            readHttpImage (url);
        else {
            String s = url.toString ();
            int pos = s.lastIndexOf ('.');
            if (pos != -1) {
                contentType = MimeTypeManager.getType (s.substring (pos + 1));
            }

            InputStream in = url.openStream ();
            try {
                byte[] buff = new byte [MAX_LENGTH];
                int length;
                while ((length = in.read (buff)) != -1) baos.write (buff, 0, length);
            } finally {
                in.close ();
            }
        }
    }

    public byte[] getImageData () {
        return baos.toByteArray ();
    }

    public String getContentType () {
        return contentType;
    }

    private void readHttpImage (URL url) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection ();
        conn.setDoInput (true);
        contentType = conn.getContentType ();
        int size = conn.getContentLength ();
        if (size <= 0) size = MAX_LENGTH;
        InputStream in = conn.getInputStream ();
        try {
            byte[] buff = new byte [size];
            int length;
            while ((length = in.read (buff)) != -1) baos.write (buff, 0, length);
        } finally {
            if (in != null) in.close ();
            conn.disconnect ();
        }
    }
}